﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sinacor.OMM.HealthMonitor;
using System.Threading;
using Sinacor.OMM.HealthMonitor.Client;
using Sinacor.OMM.HealthMonitor.Entity;
using Sinacor.OMM.HealthMonitor.Collector;
using System.Diagnostics;
using Sinacor.OMM.HealthMonitor.Collector.SharedHealthDataMemoryStorage.Receiver;
using Sinacor.OMM.HealthMonitor.Server;
using Sinacor.OMM.HealthMonitor.Collector.SharedHealthDataMemoryStorage.Router;
using Sinacor.OMM.HealthMonitor.Collector.SharedHealthDataMemoryStorage.Dumper;
using Sinacor.OMM.HealthMonitor.Collector.SharedHealthDataMemoryStorage.HftProcessor;
using Sinacor.OMM.HealthMonitor.Collector.SharedHealthDataMemoryStorage.OrderExecutor;
using Sinacor.OMM.HealthMonitor.Entity.Receiver;

namespace HealthMonitorTester
{
    public partial class formTest : Form
    {
        public formTest()
        {
            InitializeComponent();
        }

        private HealthMonitorMain _healthMonitorMain;
        private HealthMonitorClient _healthMonitorClient;

        private HealthMonitorCollector _healthMonitorCollector;
        private ReceiverShdms _receiverShdms = ReceiverShdms.GetSharedStorage();
        private RouterShdms _routerShdms = RouterShdms.GetSharedStorage();
        private DumperShdms _dumperShdms = DumperShdms.GetSharedStorage();
        private HftProcessorShdms _HftProcessorShdms = HftProcessorShdms.GetSharedStorage();
        private OrderExecutorShdms _orderExecutorShdms = OrderExecutorShdms.GetSharedStorage();

        private int _clientTotalHeartBeatReceived = 0;
        private int _serverTotalHeartBeatReceived = 0;

        private void btnStartServer_Click(object sender, EventArgs e)
        {
            btnStartServer.Enabled = false;

            _healthMonitorMain = new HealthMonitorMain();

            Thread thr = new Thread(new ThreadStart(_healthMonitorMain.Run));
            thr.Start();

            btnStopServer.Enabled = true;
        }

        private void btnStopServer_Click(object sender, EventArgs e)
        {
            btnStopServer.Enabled = false;

            if (_healthMonitorMain != null)
                _healthMonitorMain.Dispose();

            btnStartServer.Enabled = true;
        }

        private void btnStartClient_Click(object sender, EventArgs e)
        {
            btnStartClient.Enabled = false;

            _healthMonitorClient = HealthMonitorClient.GetInstance();

            _healthMonitorClient.OnConnectEvent += new HealthMonitorClient.ConnectHandler(_healthMonitorClient_OnConnectEvent);
            _healthMonitorClient.OnHealthStatusEvent += new HealthMonitorClient.HealthStatusHandler(_healthMonitorClient_OnHealthStatusEvent);
            _healthMonitorClient.OnHeartBeatReceivedEvent += new HealthMonitorClient.HeartBeatHandler(_healthMonitorClient_OnHeartBeatReceivedEvent);
            _healthMonitorClient.OnDisconnectEvent += new HealthMonitorClient.DisconnectHandler(_healthMonitorClient_OnDisconnectEvent);

            _healthMonitorClient.Start();

            btnStopClient.Enabled = true;
        }

        void _healthMonitorClient_OnDisconnectEvent()
        {
            SetText(txtConnStatus, "Disconnected");
        }

        void _healthMonitorClient_OnConnectEvent()
        {
            SetText(txtConnStatus, "Connected");
        }

        private void btnStopClient_Click(object sender, EventArgs e)
        {
            btnStopClient.Enabled = false;

            if (_healthMonitorClient != null)
                _healthMonitorClient.Dispose();

            _healthMonitorClient = null;

            btnStartClient.Enabled = true;
        }


        void _healthMonitorClient_OnHeartBeatReceivedEvent()
        {
            _clientTotalHeartBeatReceived++;
            SetText(txtHeartBeat, _clientTotalHeartBeatReceived.ToString());
        }

        void _healthMonitorClient_OnHealthStatusEvent(Sinacor.OMM.HealthMonitor.Entity.HealthData healthData)
        {
            string text = string.Empty;

            if (healthData.ReceiverHealthStatus == null)
                text += "Receptor Morreu! \r\n";
            else
                text += healthData.ReceiverHealthStatus.ProcessDataInfo.HandleCount.ToString() + "\r\n";

            if (healthData.DumperHealthStatus == null)
            {
                text += "Dumper Morreu! \r\n";
            }
            else
            {
                text += "Dumper ! \r\n";
                text += "Diretorio..............: " + healthData.DumperHealthStatus.DumpRootPath + "\r\n";
                text += "Mensagens por segundo..: " + healthData.DumperHealthStatus.SavedMessagesPerSecond + "\r\n";
                text += "Handle Count...........: " + healthData.DumperHealthStatus.ProcessDataInfo.HandleCount + "\r\n";
                text += "Nome da máquina........: " + healthData.DumperHealthStatus.ProcessDataInfo.MachineName + "\r\n";
                text += "IP da máquina..........: " + healthData.DumperHealthStatus.ProcessDataInfo.MachineIPAddress + "\r\n";

                text += "MSMQ Dumper ! \r\n";
                text += "Fila Acessível.........: " + healthData.DumperHealthStatus.MsmqDumper.QueueAcessible + "\r\n";
                text += "Mensagens na Fila......: " + healthData.DumperHealthStatus.MsmqDumper.QueuedMessages + "\r\n";
                text += "Tamanho da Fila........: " + healthData.DumperHealthStatus.MsmqDumper.QueueBytesSize + "\r\n";
                text += "Path...................: " + healthData.DumperHealthStatus.MsmqDumper.QueuePath + "\r\n";
            }
            SetText(txtHealthStatus, text);
        }

        private delegate void dSetText(TextBox textBox, string texto);
        private void SetText(TextBox textBox, string texto)
        {
            if (textBox.InvokeRequired)
            {
                try
                {
                    dSetText d = new dSetText(SetText);
                    this.Invoke(d, new object[] { textBox, texto });
                }
                catch (Exception) { }
            }
            else
                textBox.Text = texto;
        }

        private void formTest_FormClosed(object sender, FormClosedEventArgs e)
        {
            btnStopServer_Click(sender, new EventArgs());
        }

        private void formTest_FormClosing(object sender, FormClosingEventArgs e)
        {
            btnStopServer_Click(sender, new EventArgs());
            btnStopClient_Click(sender, new EventArgs());
            btnStopCollector_Click(sender, new EventArgs());
        }

        private void btnStartCollector_Click(object sender, EventArgs e)
        {
            btnStartCollector.Enabled = false;
            if (_healthMonitorCollector == null)
            {
                _healthMonitorCollector = HealthMonitorCollector.GetInstance();
                //_healthMonitorCollector.AddHealthRequestListener(HealthRequestListener, HealthType.Receiver);
                //_healthMonitorCollector.AddHealthRequestListener(RouterHealthRequestListener, HealthType.Router);
                //_healthMonitorCollector.AddHealthRequestListener(OrderHealthRequestListener, HealthType.Executor);
                _healthMonitorCollector.AddHealthRequestListener(HftHealthRequestListener, HealthType.HftProcessor);
                //_healthMonitorCollector.AddHealthRequestListener(DumperHealthRequestListener, HealthType.Dumper);
            }
            btnStopCollector.Enabled = true;
        }

        int _teste = 0;

        private object OrderHealthRequestListener()
        {
            _orderExecutorShdms.OrderExecutorDataInfo.OrderExecutor.LimitProcedureExecutionTime = 100;
            _orderExecutorShdms.OrderExecutorDataInfo.OrderExecutor.NextScheduleProcedure = TimeSpan.MinValue.ToString();
            _orderExecutorShdms.OrderExecutorDataInfo.OrderExecutor.NumberOfExceptionsDataBase = 2;
            _orderExecutorShdms.OrderExecutorDataInfo.OrderExecutor.ProcedureExecutionTime = 50;
            return _orderExecutorShdms;
        }

        private object HftHealthRequestListener()
        {
            _HftProcessorShdms.HFTProcessorDataInfo.MessageProcessor.TotalMessages = 123;
            _HftProcessorShdms.HFTProcessorDataInfo.MessageProcessor.WaitingOpenOrderAverageTime = 12M;
            _HftProcessorShdms.HFTProcessorDataInfo.MessageProcessor.LastMessageTime = DateTime.Now;
            _HftProcessorShdms.HFTProcessorDataInfo.MessageProcessor.MessagesPerSecond = 12;
            _HftProcessorShdms.HFTProcessorDataInfo.Database.OperationAverageTime = 32;
            _HftProcessorShdms.HFTProcessorDataInfo.Database.SuccessfulTriesConnection = 1;
            _HftProcessorShdms.HFTProcessorDataInfo.Database.UnsuccessfulTriesConnection = 2;
            _HftProcessorShdms.HFTProcessorDataInfo.ProcessData.PrivateMemory = 123;
            _HftProcessorShdms.HFTProcessorDataInfo.ProcessData.HandleCount = 21;
            _HftProcessorShdms.HFTProcessorDataInfo.ProcessData.ThreadCount = 12;
            _HftProcessorShdms.HFTProcessorDataInfo.ProcessData.PrivilegedProcessorTime = TimeSpan.MinValue.ToString();
            _HftProcessorShdms.HFTProcessorDataInfo.ProcessData.InitializedDate = DateTime.Now;
            _HftProcessorShdms.HFTProcessorDataInfo.ProcessData.ThreadId = "ADSFERuhfeajh";
            _HftProcessorShdms.HFTProcessorDataInfo.ProcessData.ProcessId = "ASFDnsadfhbesajb fjha";
            _HftProcessorShdms.HFTProcessorDataInfo.ProcessData.MachineMacAddress = "bahbbvsabkjsanfkjsna";
            _HftProcessorShdms.HFTProcessorDataInfo.ProcessData.MachineName = "sbadhbfjsdv";
            _HftProcessorShdms.HFTProcessorDataInfo.ProcessData.MachineIPAddress = "fbdfsabjhvdbsjhav";
            _HftProcessorShdms.HFTProcessorDataInfo.Msmq.QueueAcessible = true;
            _HftProcessorShdms.HFTProcessorDataInfo.Msmq.QueuedMessages = 2313;
            _HftProcessorShdms.HFTProcessorDataInfo.Msmq.QueueBytesSize = 123;
            _HftProcessorShdms.HFTProcessorDataInfo.TotalMsmqConnectionRetries = 123;

            return _HftProcessorShdms;
        }

        //private object DumperHealthRequestListener()
        //{
        //    _dumperShdms.DumperDataInfo.MsmqDumper.QueuePath = "STRINGAFSDGRSDJGSKRSKBVRSEAMDFFD";
        //    _dumperShdms.DumperDataInfo.MsmqDumper.QueuedMessages++;
        //    _dumperShdms.DumperDataInfo.MsmqDumper.QueueBytesSize = 456;
        //    _dumperShdms.DumperDataInfo.MsmqDumper.QueueAcessible = true;
        //    _dumperShdms.DumperDataInfo.MsmqDumper.MessagesPerSecond = 789;
        //    _dumperShdms.DumperDataInfo.MsmqDumper.LimitQueueAcessible = true;
        //    _dumperShdms.DumperDataInfo.MsmqDumper.LimitQueueBytesSize = long.MaxValue;
        //    _dumperShdms.DumperDataInfo.MsmqDumper.LimitQueuedMessages = long.MaxValue;
        //    _dumperShdms.DumperDataInfo.SavedMessagesPerSecond = 21;
        //    _dumperShdms.DumperDataInfo.DumpRootPath = "TOLIGADO";

        //    _dumperShdms.DumperDataInfo.ProcessDataInfo.PrivateMemory = 123;
        //    _dumperShdms.DumperDataInfo.ProcessDataInfo.HandleCount = 456;
        //    _dumperShdms.DumperDataInfo.ProcessDataInfo.ThreadCount = 789;
        //    _dumperShdms.DumperDataInfo.ProcessDataInfo.PrivilegedProcessorTime = TimeSpan.MinValue;
        //    _dumperShdms.DumperDataInfo.ProcessDataInfo.InitializedDate = DateTime.Now;

        //    _dumperShdms.DumperDataInfo.ProcessDataInfo.ThreadId = "BOTOPANOISBEBE";
        //    _dumperShdms.DumperDataInfo.ProcessDataInfo.ProcessId = "IEIEIEIEIEIEEEEE";

        //    _dumperShdms.DumperDataInfo.ProcessDataInfo.MachineName = "SEXYMACHINE";
        //    _dumperShdms.DumperDataInfo.ProcessDataInfo.MachineIPAddress = "IPMACHINE";

        //    return _dumperShdms;
        //}

        //private object RouterHealthRequestListener()
        //{
        //    _routerShdms.RouterDataInfo.MessageRouterInfo.RoutedMessagesForSecond = 12;
        //    _routerShdms.RouterDataInfo.MessageRouterInfo.DefaultFlowRoutedMessagesQuantity = 123;
        //    _routerShdms.RouterDataInfo.MessageRouterInfo.OptimizedRoutedMessagesQuantity = 456;
        //    _routerShdms.RouterDataInfo.MessageRouterInfo.HftRoutedMessagesQuantity = 789;
        //    _routerShdms.RouterDataInfo.MessageRouterInfo.MemoryControlledOrdersQuantity = 3;
        //    _routerShdms.RouterDataInfo.MessageRouterInfo.InternalQueuedMessages_02_Quantity = 99;
        //    _routerShdms.RouterDataInfo.DataBaseProcessInfo.BlockProcessingAverageQuantity = 3;
        //    _routerShdms.RouterDataInfo.DataBaseProcessInfo.DataBaseInsertAverageTime = 4;
        //    _routerShdms.RouterDataInfo.DataBaseProcessInfo.DataBaseSucessfulConnectionRetries = 6;
        //    _routerShdms.RouterDataInfo.DataBaseProcessInfo.DataBaseUnsucessfulConnectionRetries = 9;
        //    _routerShdms.RouterDataInfo.MessageReceiverInfo.TranslatedMessagesForSecond = 100;
        //    _routerShdms.RouterDataInfo.MessageReceiverInfo.InternalQueuedMessages_01_Quantity = 10000;
        //    _routerShdms.RouterDataInfo.MessageReceiverInfo.MsmqConnectionsRetries = 2;
        //    _routerShdms.RouterDataInfo.MessageReceiverInfo.MessagesReceivedQuantity = 3;
        //    _routerShdms.RouterDataInfo.ProcessDataInfo.PrivateMemory = 12;
        //    _routerShdms.RouterDataInfo.ProcessDataInfo.HandleCount = 23;
        //    _routerShdms.RouterDataInfo.ProcessDataInfo.ThreadCount = 34;
        //    _routerShdms.RouterDataInfo.ProcessDataInfo.PrivilegedProcessorTime = TimeSpan.MinValue;
        //    _routerShdms.RouterDataInfo.ProcessDataInfo.InitializedDate = DateTime.Now;
        //    _routerShdms.RouterDataInfo.ProcessDataInfo.ThreadId = "aaaaa";
        //    _routerShdms.RouterDataInfo.ProcessDataInfo.ProcessId = "bbbb";
        //    _routerShdms.RouterDataInfo.ProcessDataInfo.MachineMacAddress = "MACADDRESSSSS";
        //    _routerShdms.RouterDataInfo.ProcessDataInfo.MachineName = "Name";
        //    _routerShdms.RouterDataInfo.ProcessDataInfo.MachineIPAddress = "ABADDSGEFSRE";


        //    return _routerShdms;
        //}

        //private object HealthRequestListener()
        //{

        //    //            _receiverShdms.ReceiverDataInfo.ProcessDataInfo.HandleCount = _teste++;


        //    _receiverShdms.ReceiverDataInfo.StatisticInfo.lReceivedMessagesQuantity = 200;
        //    _receiverShdms.ReceiverDataInfo.StatisticInfo.LastReceivedMessageTimeStamp = DateTime.Now;
        //    _receiverShdms.ReceiverDataInfo.StatisticInfo.ReceivedMessagesForSecond = 300;
        //    _receiverShdms.ReceiverDataInfo.StatisticInfo.LastReceivedMessageId = "_lastMsgIdReceived";
        //    _receiverShdms.ReceiverDataInfo.StmConnectionInfo.ErrorEventsQuantity = 400;
        //    _receiverShdms.ReceiverDataInfo.StmConnectionInfo.SuccessfulConnectionsQuantity = 3;
        //    _receiverShdms.ReceiverDataInfo.StmConnectionInfo.UnsuccessfulConnectionsQuantity = 2;
        //    _receiverShdms.ReceiverDataInfo.ProcessDataInfo.PrivateMemory = 123;
        //    _receiverShdms.ReceiverDataInfo.ProcessDataInfo.HandleCount = 456;
        //    _receiverShdms.ReceiverDataInfo.ProcessDataInfo.ThreadCount = 789;
        //    _receiverShdms.ReceiverDataInfo.ProcessDataInfo.PrivilegedProcessorTime = TimeSpan.MinValue;
        //    _receiverShdms.ReceiverDataInfo.ProcessDataInfo.InitializedDate = DateTime.Now;
        //    _receiverShdms.ReceiverDataInfo.ProcessDataInfo.ThreadId = "ABACATE";
        //    _receiverShdms.ReceiverDataInfo.ProcessDataInfo.ProcessId = "COM MAMAO";
        //    _receiverShdms.ReceiverDataInfo.ProcessDataInfo.MachineName = "There is no place like";
        //    _receiverShdms.ReceiverDataInfo.ProcessDataInfo.MachineIPAddress = "127.0.0.1";
        //    _receiverShdms.ReceiverDataInfo.MsmqConnectionInfo.ReceiverQueue.QueueAcessible = true;
        //    _receiverShdms.ReceiverDataInfo.MsmqConnectionInfo.ReceiverQueue.QueuedMessages = 123;
        //    _receiverShdms.ReceiverDataInfo.MsmqConnectionInfo.ReceiverQueue.QueueBytesSize = 456;
        //    _receiverShdms.ReceiverDataInfo.StmConnectionInfo.Connected = true;
        //    _receiverShdms.ReceiverDataInfo.ProcessDataInfo.InitializedDate = DateTime.Now;

        //    return _receiverShdms;
        //}

        private void btnStopCollector_Click(object sender, EventArgs e)
        {
            btnStopCollector.Enabled = false;
            if (_healthMonitorCollector != null)
            {
                _healthMonitorCollector.Dispose();
                _healthMonitorCollector = null;
            }
            btnStartCollector.Enabled = true;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            for (int idx = 0; idx < 90; idx++)
            {
                Process.Start("telnet.exe", "localhost 5252");
                Thread.Sleep(500);
            }
        }

    }
}
